package com.vinobase.controller.management;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyFactory;
import com.vinobase.authentication.AppRole;
import com.vinobase.model.bean.User;
import com.vinobase.utils.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    private ObjectifyFactory objectifyFactory;

    @RequestMapping(value="/management/user/create.html", method=RequestMethod.GET)
    protected String getCreateForm(Model model){
        model.addAttribute(new User());
        return "management/user/create";
    }


    @RequestMapping(value="/management/user/list.html")
    protected String getList(Model model) {

        Objectify ofy = objectifyFactory.begin();
        List<User> users = ofy.query(User.class).list();

        model.addAttribute("users", users);
        return "management/user/list";
    }

    @RequestMapping(value="management/user/create.html", method=RequestMethod.POST)
    protected String create(@Valid User user, BindingResult result, Model model){
        if (result.hasErrors()) {
                    return "management/user/create";
        }
        if(user.isEnabled() && user.getAuthority().equals(AppRole.DISABLED))
            user.setAuthority(AppRole.USER);
        if(!user.isEnabled() && !user.getAuthority().equals(AppRole.DISABLED))
            user.setAuthority(AppRole.DISABLED);
        Objectify ofy = objectifyFactory.begin();
        ofy.put(user);

        return getList(model);
    }

    @RequestMapping(value="/management/user/{id}.html", method=RequestMethod.GET)
    protected String view(@PathVariable String id, Model model){
        Objectify ofy = objectifyFactory.begin();
        User user = ofy.get(User.class, id);
        if(user == null) {
            throw new ResourceNotFoundException(id);
        }
        model.addAttribute(user);
        return "management/user/create";

    }
}
